'use strict';

const locale = require('./lib/locale');
const y18n = require('y18n');
const debug = require('debug')('koa-grace:i18n');
const error = require('debug')('koa-grace-error:i18n');

/**
 * Add `i18n` middleware.
 *
 * @param {String} path locale目录
 * 
 * @param {Object} options (optional)
 * 
 * @return {Function}
 *
 * @todo 添加测试用例
 */
module.exports = function(path,options) {
	if (!path) {
		throw new Error('`default_locale_root` config required.');
	}
	if(!options){
		Object.assign(options,{});
	}
	Object.assign(options,{directory: path});
	if(!options.updateFiles){
		Object.assign(options,{updateFiles: true});
	}
	if(!options.locale) {
		Object.assign(options,{locale:'en-us'});
	}
	if(!options.locales) {
		Object.assign(options,{
			'zh':'zh-cn',
			'en':'en-us'			  
		});
	}
	if(!options.fallbackToLanguage){
		Object.assign(options,{fallbackToLanguage:true});
	}
	if(!options.cookieKey){
		Object.assign(options,{cookieKey:'locale'});
	}
	if(!options.queryKey){
		Object.assign(options,{queryKey:'lang'});
	}
	
	//设置locale的全局变量
	const reqLocale = locale(options);
	const i18n = y18n(options);

	const perfectLocale = function(request){
		var localeValue = reqLocale.getLocaleFromQuery(request);
		if(localeValue){
			i18n.setLocale(localeValue);
			return;
		}
		localeValue = reqLocale.getLocaleFromCookie(request);
		if(localeValue){
			i18n.setLocale(localeValue);
			return;
		}
		localeValue = reqLocale.getLocaleFromHeader(request);
		if(localeValue){
			i18n.setLocale(localeValue);
			return;
		}
	}

	
	return async function i18nMiddleware(ctx, next) {
		//处理i18n，把函数__作为ctx.state输入，在之前需要使用request来获取locale
		perfectLocale(ctx.request);
		
		if(ctx.state.__) return await next();
		Object.assign(ctx.state, {
			__ : i18n.__,
			__n: i18n.__n
		});
		await next();
	};
}